const resolveApp = require("./path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const VueLoaderPlugin = require("vue-loader/lib/plugin");
const TerserPlugin = require("terser-webpack-plugin");
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const webpack = require("webpack");

const { merge } = require("webpack-merge");

const prodConfig = require("./webpack.prod");
const devConfig = require("./webpack.dev");

const commonConfig = (isProduction) => ({
  entry: {
    main: "./src/main.js",
    index: "./src/index.js",
  },
  output: {
    filename: "js/[name].bundle.js",
    path: resolveApp("./build"),
    chunkFilename: "[name].chunk.js",
    // publicPath: "https://lyc.com/cdn",
  },
  resolve: {
    extensions: [".js", ".json", ".wasm", ".mjs", ".vue", ".jsx"],
    alias: {
      "@": resolveApp("./src"),
      pages: resolveApp("./src/pages"),
    },
  },
  optimization: {
    minimizer: [
      new TerserPlugin({
        extractComments: false,
      }),
    ],
    chunkIds: "deterministic",
    splitChunks: {
      chunks: "all",
      minSize: 20000,
      minChunks: 1,
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          filename: "js/[id]_vendors.js",
          name: "chunk-vendors.js",
          priority: -10,
        },
        default: {
          minChunks: 2,
          filename: "js/common_[id].js",
          priority: -20,
        },
      },
    },
    runtimeChunk: {
      name: function(entrypoint) {
        return `lyc-${entrypoint.name}`;
      },
    },
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/i,
        use: "babel-loader",
      },
      {
        test: /\.vue$/i,
        use: "vue-loader",
      },
      {
        test: /\.css$/i,
        use: [
          process.env.NODE_ENV ? MiniCssExtractPlugin.loader : 'style-loader',
          {
            loader: "css-loader",
            options: {
              importLoaders: 2,
            },
          },
          "postcss-loader",
        ],
      },
    ],
  },
  plugins: [
    new HtmlWebpackPlugin({ template: resolveApp("./index.html") }),
    new VueLoaderPlugin(),
    // new webpack.ProviderPlugin({
    //   axios: 'axios',
    //   axios: ['axios', 'get']
    // })
  ],
})

module.exports = function(env) {
  const isProduction = env.production;
  process.env.NODE_ENV = isProduction ? "production" : "development";

  const config = isProduction ? prodConfig : devConfig;

  return merge(commonConfig(isProduction), config);
};
